import { legacy_createStore, applyMiddleware } from "redux"
import logger from "redux-logger"
import thunk from "redux-thunk";
import { json } from "stream/consumers";
import { GETIMGS, ADDSHOPCAR, GETINFO, GETLIST, ALLACTION, ALLSTATE, GETOBJ } from "../types/store.d"

const initialState = {
  listArr: JSON.parse(window.localStorage.getItem("listArr") as string)||[],
  infoArr: JSON.parse(window.localStorage.getItem("infoArr") as string)||[],
  imgsArr: JSON.parse(window.localStorage.getItem("imgsArr") as string)||[],
  obj: JSON.parse(window.localStorage.getItem("obj") as string)||{},
  shopArr: JSON.parse(window.localStorage.getItem("shopArr") as string)||[]
}

const reducer = (state: ALLSTATE = initialState, { type, payload }: ALLACTION) => {
  const localSave = (title: string, data: ALLACTION) => {
    window.localStorage.setItem(title, JSON.stringify(data))
  }
  switch (type) {
    case GETIMGS:
      let newarr=[...state.imgsArr]
      newarr=payload;
      state.imgsArr = newarr
      // localSave("imgsArr", state.imgsArr)
      window.localStorage.setItem("imgsArr", JSON.stringify(state.imgsArr))
      return state
    case GETINFO:
      let newarr1=[...state.infoArr]
      newarr1=payload;
      state.infoArr = newarr1
      // localSave("infoArr", state.infoArr)
      window.localStorage.setItem("infoArr", JSON.stringify(state.infoArr))
      return state
    case GETLIST:
      let newarr2=[...state.listArr]
      newarr2=payload;
      state.listArr = newarr2
      // localSave("listArr", state.listArr)
      window.localStorage.setItem("listArr", JSON.stringify(state.listArr))
      return state
    case GETOBJ:
      let newArr = [...state.listArr]
      newArr.forEach(item => {
        item.info.filter(item => {
          if (item.id === payload) {
            console.log(item, "=====");
            state.obj = item
          }
        })
      });
      // localSave("obj", state.obj)
      window.localStorage.setItem("obj", JSON.stringify(state.obj))
      return state
    case ADDSHOPCAR:
      console.log(payload,"3333");
      let Arr = [...state.shopArr]
      const isFlag = Arr.some(item => item.id === payload.id)
      console.log(isFlag);
      if (isFlag) {
        Arr.forEach(item => {
          if (item.id === payload.id) {
            // item.num++;
          }
        })
      } else {
        Arr.push(payload)
      }
      state.shopArr=Arr;
      window.localStorage.setItem("shopArr", JSON.stringify(state.shopArr))
      // localSave("shopArr", state.shopArr)
      return state
    default:
      return state
  }
}
const store = legacy_createStore(reducer, applyMiddleware(logger, thunk))
export default store